﻿using System.Data;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Yamfinder.Data.Tests
{
    [TestClass]
    public class UsersIntegrationTests
    {
        private IDataSource _dataSource;
        private IUserRepository _usersRepository;

        [TestInitialize]
        public void Init()
        {
            _dataSource = new DataSource();
            _usersRepository = new UserRepository(_dataSource);
        }

        [TestMethod]
        public void IntergrationTest()
        {
            //Test Insert
            _usersRepository.Insert(new User() { Firstname = "Blaaaa", IsAdmin = false, Lastname = "Bla de blaaa", Password = "XYJFJD", Username = "TestUsersValue1000"});
            _usersRepository.Insert(new User() { Firstname = "Blaaaa", IsAdmin = false, Lastname = "Bla de blaaa", Password = "XYJFJD", Username = "TestUsersValue2000" });

            //Test Query
            Assert.IsTrue(_usersRepository.Query().Where(x => x.Username.StartsWith("TestUsersValue")).Count() == 2);

            //Test Get w. Name
            var value1000 = _usersRepository.Get("TestUsersValue1000");

            Assert.IsNotNull(value1000);
            Assert.AreEqual(value1000.IsAdmin, false);

            //Test Save
            value1000.IsAdmin = true;
            _usersRepository.Save(value1000);

            //Test Get w. Id
            value1000 = _usersRepository.Get(value1000.Id);

            Assert.IsNotNull(value1000);
            Assert.AreEqual(value1000.IsAdmin, true);

            var value2000 = _usersRepository.Get("TestUsersValue2000");

            Assert.IsNotNull(value2000);

            //Test Remove w. Id and Text
            _usersRepository.Remove(value2000.Id);
            _usersRepository.Remove(value1000.Username);

            Assert.IsTrue(_usersRepository.Query().Where(x => x.Username.StartsWith("TestUsersValue")).Count() == 0);
        }

        [TestMethod]
        [ExpectedException(typeof(DataException))]
        public void DuplicateUserNamesTest()
        {
            //Should not let me have duplciate user names
            _usersRepository.Insert(new User() { Firstname = "Blaaaa", IsAdmin = false, Lastname = "Bla de blaaa", Password = "XYJFJD", Username = "TestUsersValue1000" });

            //This should throw an exception
            _usersRepository.Insert(new User() { Firstname = "Blaaaa", IsAdmin = false, Lastname = "Bla de blaaa", Password = "XYJFJD", Username = "TestUsersValue1000" });
        }

        [TestCleanup]
        public void Cleanup()
        {
            //Just in case these are left around
            _usersRepository.Remove("TestUsersValue1000");
            _usersRepository.Remove("TestUsersValue2000");
        }
    }
}